﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

using INSTA.StockApplication.DAL;

namespace INSTA.StockApplication.BLL
{
    public class Orders
    {
        private ApplicationStockEntities _context = new ApplicationStockEntities();

        public Orders()
        {
            
        }

        public int AddOrderIntoDatabase(int client,DateTime date)
        {
            COMMANDE c = new COMMANDE();
            c.ID_STATUT = 1;
            c.DATE = date;
            c.ID = client;
            _context.Set<COMMANDE>().Add(c);
            save(_context);
            return c.ID_COMMANDE;
        }

        public bool AddLinesOrderIntoDatabase(int id,int produit,int qte)
        {
            LIGNE_COMMANDE l = new LIGNE_COMMANDE();
            l.ID_COMMANDE = id;
            l.ID_PRODUIT = produit;
            l.QUANTITE = qte;
            _context.Set<LIGNE_COMMANDE>().Add(l);
            return save(_context);
        }

        private ApplicationStockEntities UpdateQuantityIntoDatabase(ApplicationStockEntities ctx,int id,int qte)
        {
            STOCK stock = ctx.STOCKs.First(i => i.ID_PRODUIT == id);
            stock.QUANTITE_RESTANTE = stock.QUANTITE_RESTANTE - qte;
            return ctx;
        }

        public List<ViewProduitsForCommande> GetProductsForOrdersFromDatabase()
        {
            return _context.ViewProduitsForCommandes.ToList();
        }

        public List<ViewCommande> GetOrdersFromDatabase()
        {
            return _context.ViewCommandes.ToList();
        }

        public List<LIGNE_COMMANDE> GetOrdersLineFromDatabaseByCommande(int id)
        {
            var lines = from line in _context.LIGNE_COMMANDE
                        where line.ID_COMMANDE == id
                        select line;
            return lines.ToList();

        }

        public bool DeleteOrderFromDatabase(int id)
        {
            COMMANDE c = _context.COMMANDEs.First(i => i.ID_COMMANDE == id);
            _context.COMMANDEs.Remove(c);
            return save(_context);
        }

        private bool save(ApplicationStockEntities context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var s in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entite : {0} etat {1} : ", s.Entry.Entity.GetType().Name, s.Entry.State);
                    foreach (var v in s.ValidationErrors)
                    {
                        Console.WriteLine("Propriete {0}, erreur {1} : ", v.PropertyName, v.ErrorMessage);
                    }
                }
                return false;
            }
            return true;
        }
    }
}
